
<template>
  <div>
    <div class="container">
      <div class="handle-box">
        <span style="padding: 8px 8px 8px 0">标题名称：</span>
        <el-input v-model="query.keyword" placeholder="标题名称" class="handle-input mr10" @keydown="initAjaxMethod"></el-input>
        <span style="padding: 8px">文件类型：</span>
        <el-radio-group v-model="query.type" @change="initAjaxMethod">
          <el-radio :label="-1">全部</el-radio> 
          <el-radio :label="0">图片</el-radio>
          <el-radio :label="1">视频</el-radio>
        </el-radio-group>
        <span style="padding: 8px">上传时间：</span>
        <el-date-picker
          v-model="query.create_time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="initAjaxMethod"
        >
        </el-date-picker>
        <span style="padding: 8px"></span>
        <el-button
          type="success"
          size="medium"
          icon="el-icon-search"
          @click="handleSearch()"
          >搜索</el-button
        >
        <el-button
          type="warning"
          size="medium"
          icon="el-icon-refresh-left"
          @click="resultClick()"
          >重置</el-button
        >
      </div>
      <div class="handle-box" style="display: flex">
        <el-button type="primary" icon="el-icon-document-add" size="medium" @click="createMethod" v-if="roulShowList.btn1.type">新增媒资目录</el-button>
        <el-button type="primary" size="medium" icon="el-icon-user-solid" @click="gotoPage(1)"  v-if="roulShowList.btn4.type">上传记录</el-button>
        <el-button type="primary" size="medium" icon="el-icon-circle-plus-outline" @click="gotoPage(2)"  v-if="roulShowList.btn5.type">转码记录</el-button>
        <el-button type="danger" size="medium" icon="el-icon-delete" @click="delAllSelection"  v-if="roulShowList.btn3.type">批量删除</el-button>
      </div>
      <div class="handle-box" style="display: flex">
        <div class="sort-title">综合排序</div>
        <div class="sort-group" @click="sortMethod(1)">
          <span>拍摄时间</span>
          <i class="el-icon-sort-down" :class="[query.shooting_time_sort === 'desc'?'sort-active':'']"></i> 
          <i class="el-icon-sort-up" :class="[query.shooting_time_sort === 'asc'?'sort-active':'']"></i>
        </div>
        <div class="sort-group" @click="sortMethod(2)">
          <span>上传时间</span>
          <i class="el-icon-sort-down" :class="[query.create_time_sort === 'desc'?'sort-active':'']"></i>
          <i class="el-icon-sort-up" :class="[query.create_time_sort === 'asc'?'sort-active':'']"></i>
        </div>
      </div>
      <el-table
        :data="tableData"
        border
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="序号" width="55">
          <template slot-scope="scope">{{
            scope.$index + (query.pageIndex - 1) * query.pageSize + 1
          }}</template>
        </el-table-column>
        <el-table-column label="标题" align="center">
          <template slot-scope="scope">{{ scope.row.title }}</template>
        </el-table-column>
        <el-table-column label="类型" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.type == 0">图片</span>
            <span v-if="scope.row.type == 1">视频</span>
          </template>
        </el-table-column>
        <el-table-column label="拍摄时间" align="center">
          <template slot-scope="scope">{{ scope.row.shooting_time }}</template>
        </el-table-column>
        <el-table-column label="上传时间" align="center">
          <template slot-scope="scope">{{ scope.row.create_time }}</template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-plus"
              type="text"
              @click="handleSource(scope.row)"
              >资源编辑</el-button
            >
            <span style="padding: 8px"></span>
            <el-button
              v-if="roulShowList.btn2.type"
              icon="el-icon-edit"
              type="text"
              @click="typeAjaxMethod(2,scope.row)"
              >编辑</el-button
            >
            <span style="padding: 8px"></span>
            <el-popconfirm
              v-if="roulShowList.btn3.type"
              title="确定删除吗？"
              @confirm="handleDelete(scope.row.id,scope.row.title)"
            >
              <el-button
                type="text"
                slot="reference"
                icon="el-icon-delete"
                style="color: #f56c6c"
                >删除</el-button
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          layout="sizes,total, prev, pager, next, jumper"
          :current-page="query.pageIndex"
          :page-size="query.pageSize"
          :page-sizes="[10,20, 50, 100, 150, 200]"
          @size-change="handleSizeChange"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
    <el-dialog :title="dialogTitle" :visible.sync="dialog" width="50%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="类型">
          <el-radio-group v-model="ruleForm.type" :disabled="disabled">
            <el-radio :label="0">图片</el-radio>
            <el-radio :label="1">视频</el-radio>
          </el-radio-group>
        </el-form-item>
         <el-form-item label="标题" prop="title">
          <el-input v-model.trim="ruleForm.title" placeholder="标题名称"></el-input>
        </el-form-item>
        <el-form-item label="拍摄时间" prop="shooting_time">
          <el-date-picker
                type="date"
                placeholder="选择日期"
                v-model="ruleForm.shooting_time"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
        </el-form-item>
        <el-form-item label="标签类别" prop="cate_ids">
          <!-- <el-cascader
            v-model="ruleForm.cate_ids"
            :collapse-tags="true"
            :options="treeData"
            :props="{ multiple: true,value:'id',children: 'children',label: 'title'}"
            collapse-tags
            clearable></el-cascader> -->
            <el-tree
              ref="tree"
              :data="treeData"
              show-checkbox
              node-key="id"
              :default-checked-keys="cate_ids"
              @check-change="cascaderClick"
              :props="{children: 'children',label: 'title'}">
            </el-tree>
        </el-form-item>
        <el-form-item label="详情">
          <el-input type="textarea" v-model.trim="ruleForm.content" placeholder="详情" :rows="5" maxlength="500" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="submitMethod">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "resourceUpload",
  data() {
    return {
      treeData:[],
      dialog: false,
      disabled:false,
      query: {
        type: -1,
        create_time: [],
        pageIndex: 1,
        pageSize: 10,
        keyword: "",
        shooting_time_sort:'',
        create_time_sort:'',
      },
      tableData: [],
      pageTotal:0,
      multipleSelection: [], 
      roulShowList: {
          btn1: { rule: 'homepage,upload,add', type: false, name: '新增媒资目录' },
          btn2: { rule: 'homepage,upload,edit', type: false, name: '编辑' },
          btn3: { rule: 'homepage,upload,del', type: false, name: '删除' },
          btn4: { rule: 'homepage,upload,upload_list', type: false, name: '上传记录' },
          btn5: { rule: 'homepage,upload,compress_list', type: false, name: '转码记录' }
      },
      ruleForm: {
        title: '',
        content: '',
        cate_ids: '', 
        type: 0,
        shooting_time: ''
      },
      cate_ids:[],
      rules: {
        title: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        shooting_time: [
          { required: true, message: '请选择拍摄日期', trigger: 'blur' }
        ]
      },
      dialogTitle:'新增',
      media_id:null
    };
  },
  created() {
      this.roleMethod();
  },
  activated(){
    let ifDoFresh=window.sessionStorage.getItem('jqjtIsBack');
    if(ifDoFresh ==1){
      this.resultClick()
    }
  },
  methods: {
    cascaderClick(){
      // ruleForm.cate_ids
      let nodes=this.$refs.tree.getCheckedNodes(),cate_ids=[];
      nodes.forEach(item=>{
        if(Array.isArray(item.children) && item.children.length>0){
          cate_ids.push(...cate_ids,...item.children.map(item=>item.id))
        }
      })
      this.ruleForm.cate_ids=cate_ids.join(',')
    },
    handleSource(data){
      this.$router.push({path:'/resourceEdit',query:{id:data.id,type:2}})
    },
    gotoPage(flag){
      let path=flag == 1?'/uploadProgress':'/transcodingProgress';
      this.$router.push({path})
    },
    //重置
    resultClick() {
      this.query={
        type: -1,
        create_time: [],
        pageIndex: 1,
        pageSize: 10,
        keyword: "",
        shooting_time_sort:'',
        create_time_sort:'',
      },
      this.initAjaxMethod();
    },
    successMethod() {
      this.dialog = false;
      this.$set(this.query, "pageIndex", 1);
      this.initAjaxMethod();
    },
    // 触发搜索按钮
    handleSearch() {
      this.$set(this.query, "pageIndex", 1);
      this.initAjaxMethod();
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, "pageIndex", val);
      this.initAjaxMethod();
    },
    handleSizeChange(e){
      this.query.pageSize=e;
      this.initAjaxMethod();
    },
    // 删除操作
    handleDelete(id,detail) {
      this.delAjaxMethod(id,detail);
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    sortMethod(flag){
      let {shooting_time_sort,create_time_sort}=this.query,
      shooting='',
      create='';
      if(flag == 1){
        if(shooting_time_sort == ''){
          shooting='desc';
        }else{
          shooting=shooting_time_sort === 'asc'?'desc':'asc';
        }
        create='';
      }else{
        if(create_time_sort == ''){
          create='desc';
        }else{
          create=create_time_sort === 'asc'?'desc':'asc';
        }
        shooting='';
      }
      this.query.shooting_time_sort=shooting;
      this.query.create_time_sort=create;
      this.initAjaxMethod();
    },
    delAllSelection() {
      if(this.multipleSelection.length<=0){
        return this.$message.error('请选择一个目录');
      }
      this.$confirm("确定要删除吗？", "提示", {
        type: "warning",
      })
        .then(() => {
          let arr = [],detail=[];
          this.multipleSelection.forEach((item) => {
            arr.push(item.id);
            detail.push(item.title);
          });
          this.delAjaxMethod(arr.join(","),detail.join(','));
        })
        .catch(() => {});
    },
    createMethod() {
      // bus.$emit('global-uploader-open', true);
      this.ruleForm={
        title: '',
        content: '',
        cate_ids: '',
        type: 0,
        shooting_time: ''
      },
      this.cate_ids=[];
      this.dialog=true;
      this.disabled=false;
      this.media_id=null;
      this.dialogTitle='新增';
      setTimeout(()=>{
        this.$refs['ruleForm'].clearValidate()
      },200)
      this.typeAjaxMethod();
    },
    // 编辑操作
    handleEdit(data) {
      // let arr=[];
      // this.treeData.forEach(item=>{
      //   item.children.forEach(val=>{
      //     if(data.cateids && data.cateids.indexOf(val.id.toString())!==-1){
      //       arr.push([item.id,val.id])
      //     }
      //   })
      // })
      this.cate_ids=data.cateids?data.cateids.split(','):[];
      this.ruleForm={
        title: data.title,
        content: data.content,
        cate_ids: data.cateids,
        type: data.type,
        shooting_time: data.shooting_time
      },
      this.dialog=true;
      this.media_id=data.id;
      this.disabled=true;
      this.dialogTitle='编辑';
      setTimeout(()=>{
        this.$refs['ruleForm'].clearValidate()
      },200)
    },
    //列表加载
    typeAjaxMethod(flag=1,data=null) {
      this.$http
        .post(this.$API.MEDIA_UPLOAD_TAGS)
        .then((res) => {
          if (res.code == 1) {
            let list=Array.isArray(res.data)?res.data:[],arr=[];
            list.forEach(item=>{
              let obj={
                id:item.id,
                title:item.title,
                children:[]
              }
              if(Array.isArray(item.children) && item.children.length>0){
                item.children.forEach(val=>{
                  obj.children.push({
                    id:val.id,
                    title:val.title
                  })
                })
              }
              arr.push(obj)
            })
            this.treeData = arr;
            if(flag==2){
              this.handleEdit(data)
            }
          }
        })
    },
    //列表加载
    initAjaxMethod() {
      this.$http
        .post(this.$API.MEDIA_UPLOAD_INDEX, {
          page: this.query.pageIndex,
          listRows: this.query.pageSize,
          title: this.query.keyword,
          type: this.query.type==-1?'':this.query.type,
          keyword: this.query.keyword,
          create_time:  Array.isArray(this.query.create_time) && this.query.create_time.length>1?this.query.create_time.join('~'):'',
          shooting_time_sort:this.query.shooting_time_sort,
          create_time_sort:this.query.create_time_sort
        })
        .then((res) => {
          // console.log("媒资列表", res);
          if (res.code == 1) {
            this.tableData=Array.isArray(res.data.data)?res.data.data:[];
            this.pageTotal=res.data.total;
          }
        })
    },
    submitMethod(){
      this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({ text: "加载中..." });
            const url=this.media_id?this.$API.MEDIA_EDIT:this.$API.MEDIA_ADD
            if(this.media_id)this.ruleForm.media_id=this.media_id;
            // let arr=[];
            // this.ruleForm.cate_ids.forEach(item=>{
            //   if(item.length>1){
            //     arr.push(item[1])
            //   }
            // })
            // if(arr.length>0)this.ruleForm.cate_ids=arr.join(',');
            this.$http
              .post(url, this.ruleForm)
              .then((res) => {
                // console.log("公海列表", res);
                if (res.code == 1) {
                  this.$message.success("操作成功");
                  this.query.pageIndex = 1;
                  this.dialog=false;
                  this.initAjaxMethod();
                } else {
                  this.$message.error(res.msg);
                }
                loading.close();
              })
              .catch((err) => {
                loading.close();
                this.$message.error(err.msg);
              });
          } else {
           this.$message.error('有必填项目未填写');
          }
        });
      
    },
    //删除单个
    delAjaxMethod(id,detail) {
      const loading = this.$loading({ text: "加载中..." });
      this.$http
        .post(this.$API.COMPANY_DEL, { ids: id,detail:detail})
        .then((res) => {
          loading.close();
          // console.log("公海列表", res);
          if (res.code == 1) {
            this.$message.success("删除成功");
            this.initAjaxMethod();
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch((err) => {
          this.$message.error(err.msg);
        });
    },
    roleMethod(){
      this.$http.post(this.$API.GET_TRR_PAGE, { rule: 'homepage,upload' }).then((res) => {
            // console.log('页面权限', res);
            if (res.data === 'admin') {
                for (let i in this.roulShowList) {
                    this.roulShowList[i].type = true;
                }
            } else {
                res.data.forEach((item) => {
                    for (let j in this.roulShowList) {
                        if (item.rule == this.roulShowList[j].rule) {
                            this.roulShowList[j].type = true;
                        }
                    }
                });
            }
        });
    }
  },
  components: {
    // watersAdd, exhibitionTmp
  },
};
</script>

<style scoped>
.container {
  padding: 20px;
}
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: auto;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #f56c6c;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
.demo-drawer__content {
  margin: 0 auto;
  width: 80%;
  border: 1px solid #fafafa;
}
.sort-title {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}
.sort-group {
  display: flex;
  align-items: center;
  margin-left: 30px;
  font-size: 14px;
}
.sort-group:hover{
  cursor: pointer;
}
.sort-group:hover span{
  color:#409EFF;
}
.sort-group i{
  font-weight: bold;
}
.sort-active{
  color:#409EFF;
}
</style>
